<?php
/**
 * 会员信息相关
 */
namespace Control;
use Model\MemberMod;
use Model\WqFansMod;
use Model\WqMemberMod;
use Pub\cache\Cache;

class MemberControl extends Control
{
    private $Member = null;

    public function __construct()
    {
        parent::__construct();
        $this->Member = new MemberMod();
    }

    /**
     *通过用户的uid获取用户详细信息
     * @param int $_uid 用户id
     * @param int $_count 加载次数 - 系统获取用户头像昵称失败时重复请求
     * @return Array 用户数据
     */
    public function find($_uid, $_count = 0)
    {
        $_data = Cache::get(Cache::MEMBER_DETAIL, array("uid" => $_uid));
        if (!$_data || KUYUAN_DEBUG) {
            $WqMember = new WqMemberMod();
            $_data = $WqMember->findOne(array("uid" => $_uid), array("nickname", "avatar", "credit2"));
            $_data["header"] = $_data["avatar"];
            unset($_data["avatar"]);
            $_data = array_merge(
                $_data,
                $this->Member->findOne(array("uid"=>$_uid),array("phone"))
            );
            if ($_count == 0 && ((isset($_data['nickname']) && $_data['nickname'] == '') || (isset($_data['avatar']) && $_data['avatar'] == ''))) {
                Cache::remove(Cache::MEMBER_DETAIL,array("uid"=>$_uid));
                $_fans = $this->findFans($_uid);
                $WxApi = \WeAccount::create();
                $_wx_member = $WxApi->fansQueryInfo($_fans['openid']);
                $WqMember->update(array('nickname' => $_wx_member['nickname'], 'avatar' => $_wx_member['headimgurl']), array('uid' => $_uid));
                return $this->find($_uid, ++$_count);
            }
            Cache::set(Cache::MEMBER_DETAIL, $_data,array("uid" => $_uid));
        }
        return $_data;
    }

    /**
     * 设置用户信息
     * @param array $_data 设置用户信息
     * @param array $_where 修改条件
     * @return mixed
     */
    public function set(Array $_data,Array $_where)
    {
        return $this->Member->update($_data,$_where);
    }

    /**
     * 通过用户id获取粉丝信息
     * @param int $_uid 用户id
     * @return Array 粉丝信息
     */
    private function findFans($_uid)
    {
        $WqFans = new WqFansMod();
        return $WqFans->findOne(array('uid'=>$_uid),array("openid"));
    }
}